{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d1f20875-c50d-46df-906b-49ec1d0c6002",
   "metadata": {},
   "source": [
    "# 7.2 使用tf.keras.metrics.categorical_ crossentropy方法计算交叉熵损失"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c90a18b9-d8e8-431c-856c-35f1e4ed05e1",
   "metadata": {},
   "source": [
    "### 1.任务描述\n",
    "\n",
    "在三分类任务中，3个样本的标签列表为Y=[0,1,2]，经过模型计算，得到的线性输出值为：\n"
   ]
  },
  {
   "cell_type": "raw",
   "id": "e44f9098-48bb-4e23-8ea8-2b8de13eb909",
   "metadata": {},
   "source": [
    "Y_PRED=[[1.2,3.4,5.],\n",
    "        [1.2,3.4,5.],\n",
    "        [1.2,3.4,5.]]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f953478-7225-44e5-b3a5-b5f0b03a507a",
   "metadata": {},
   "source": [
    "\n",
    "要求：\n",
    "- 通过tf.keras.metrics.categorical_crossentropy方法计算交叉熵损失。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f5b4fc39-cbcf-432a-bf1e-e75e642d4b87",
   "metadata": {},
   "source": [
    "### 2.知识准备\n",
    "\n",
    "见教程。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b624ebee-980f-4c1e-b963-a24ff0b669f6",
   "metadata": {},
   "source": [
    "### 3.任务分析\n",
    "\n",
    "先通过tensorflow.one_hot方法将原始标签值Y[0,1,2]转化成Y[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]这样的独热编码格式。\n",
    "\n",
    "再把线性结果通过tensorflow.nn.softmax方法转化成预测值。\n",
    "\n",
    "通过tf.keras.metrics.categorical_crossentropy方法计算出预测值数组与实际标签数组的偏差值。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "435c6090-cfda-4f46-a550-22a368e41e4a",
   "metadata": {},
   "source": [
    "### 4.任务实施\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec75eb6c-5da3-467d-a471-ca3b47242dd6",
   "metadata": {},
   "source": [
    "执行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2ae9da58-e339-4d22-9f8d-ca255711d89e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Y_train: tf.Tensor(\n",
      "[[1. 0. 0.]\n",
      " [0. 1. 0.]\n",
      " [0. 0. 1.]], shape=(3, 3), dtype=float32)\n",
      "Y_pred: tf.Tensor(\n",
      "[[0.01827278 0.16491213 0.816815  ]\n",
      " [0.03512738 0.38721526 0.57765734]\n",
      " [0.00584551 0.9587913  0.03536325]], shape=(3, 3), dtype=float32)\n",
      "tf.Tensor(2.7643995, shape=(), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "# 三分类中的3个标签值\n",
    "Y=[0,1,2]\n",
    "# 将标签值转为独热编码格式\n",
    "Y_train=tf.one_hot(Y,depth=3)\n",
    "\n",
    "print(\"Y_train:\",Y_train)\n",
    "# 预测值\n",
    "Y_PRED=[\n",
    "          [1.2,3.4,5.],\n",
    "          [2.2,4.6,5.],\n",
    "          [3.2,8.3,5.]\n",
    "       ]\n",
    "# 将预测值转为概率数组\n",
    "Y_pred=tf.nn.softmax(Y_PRED)\n",
    "print(\"Y_pred:\",Y_pred)\n",
    "\n",
    "# 计算交叉熵损失，返回一个数组\n",
    "Loss = tf.keras.metrics.categorical_crossentropy(\n",
    "    Y_train,Y_pred\n",
    ")\n",
    "# 计算平均交叉熵损失\n",
    "Loss_mean=tf.reduce_mean(Loss)\n",
    "print(Loss_mean)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e3b3e36e-8418-4caf-af51-d8ac80e2a321",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
